<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" v-on:click="getDepartments">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>
		<!--列表-->
		<el-table :data="departments" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection" width="55">
			</el-table-column>
			<el-table-column type="index" width="60">
			</el-table-column>
			<el-table-column prop="name" label="名称" width="180" sortable>
			</el-table-column>
			<el-table-column prop="sn" label="编号" width="120" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态" width="100" sortable>
				<template scope="scope">
					<span style="color: green" v-if="scope.row.state ==0">正常</span>
					<span style="color: red" v-else-if="scope.row.state ==-1">禁用</span>
					<span style="color: gray" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="manager.username" label="管理员" width="120" sortable>
			</el-table-column>
			<el-table-column prop="parent.name" label="父部门" width="120" sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
				</template>
			</el-table-column>
		</el-table>
		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
						   :page-size="pageSize"
						   :total="total"
						   :current-page="page"
						   style="float:right;">
			</el-pagination>
		</el-col>
		<!--新增或编辑界面-->
		<el-dialog title="新增/编辑" :visible.sync="departmentFormVisible" :close-on-click-modal="false">
			<el-form :model="departmentForm" label-width="80px" :rules="departmentFormRules" ref="departmentForm">
				<el-form-item label="名称" prop="name">
					<el-input v-model="departmentForm.name" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="编码" prop="sn">
					<el-input v-model="departmentForm.sn" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="状态" prop="state">
					<el-radio-group v-model="departmentForm.state">
						<el-radio class="radio" :label="0">正常</el-radio>
						<el-radio class="radio" :label="-1">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="管理员" prop="manager">
					<template>
						<el-select v-model="departmentForm.manager" value-key="id" placeholder="请选择">
							<el-option
									v-for="item in employees"
									:key="item.id"
									:label="item.username"
									:value="item">
								<span style="float: left">{{ item.username }}</span>
								<span style="float: right; color: #8492a6; font-size: 13px">{{ item.phone }}</span>
							</el-option>
						</el-select>
					</template>
				</el-form-item>
					<el-form-item label="上级部门" prop="parent">
						<!--<el-input v-model="departmentForm.parent" auto-complete="off"></el-input>-->
						<el-cascader
								v-model="departmentForm.parent"
								:options="deptTree"
								:props="{
								 checkStrictly: true,
								 label:'name',
								 value:'id'
									 }"
								clearable></el-cascader>
					</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="departmentFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="departmentLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	import { getDepartmentListPage, removeDepartment, batchRemoveDepartment, editDepartment, addDepartment } from '../../api/api';
	export default {
		data() {
			return {
				filters: {
                    keyword: ''
				},
                departments: [],
                total: 0,
                pageSize:10,
                page: 1,
                listLoading: false,
                sels: [],//列表选中行
                deptTree:[],
                employees:[],

				departmentFormVisible: false,//新增/编辑界面是否显示
				departmentLoading: false,//忙等框
				departmentFormRules: {//申明校验规则
					name: [
						{ required: true, message: '请输入姓名', trigger: 'blur' }

					],
                    sn: [
                        { required: true, message: '请输编号', trigger: 'blur' }
                    ]

				},

				//编辑界面数据
				departmentForm: {
					id: null,
					name: '',
					sn: '',
					state: 0,
					manager: null,
					parent: null
				}

			}
		},
		methods: {
            //状态显示转换
            /*formatSex: function (row, column) {
                return row.state == 0 ? '正常' : row.state == -1 ? '禁用' : '未知';
            },*/
            handleCurrentChange(val) {
                this.page = val;
                this.getDepartments();
            },

            //获取部门列表
            getDepartments() {
                let para = {
                    currentPage: this.page,
                    pageSize: this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading = true;//开启忙等框
                /*发送axios请求，从后端拿数据*/
                this.$http.post("/department",para)
                    .then(result=>{
                        this.total = result.data.total;
                        this.departments = result.data.rows;
                        this.listLoading = false;//关闭忙等框
                    })
                    .catch(result=>{
                        this.$message({
                            message: '系统异常',
                            type: 'error'
                        });
                    })
            },

            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '温馨提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    this.$http.delete("/department/"+row.id)
                        .then(result=>{
                            result = result.data;
                            if(result.success){
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;//如果删除成功，定位到第一页
                            }else{
                                this.$message({
                                    message: '删除失败'+result.message,
                                    type: 'error'
                                });
                            }
                            this.getDepartments();//重新刷新列表
                        })
                }).catch(() => {
                });
            },

            //显示编辑界面
            handleEdit: function (index, row) {
                this.departmentFormVisible = true;//显示编辑窗口
                //Object.assign 克隆
                this.departmentForm = Object.assign({}, row);//回显数据
                //获取数据
                this.getDeptTree();
                    let dirPath = row.dirPath; // /2/5/11
                    if(dirPath){
                    let tmp = [];
                    if(dirPath){
                        let dirPaths =  dirPath.trim().split("/"); //['','2','5','11']
                        for(let i=1;i<dirPaths.length-1;i++){
                            tmp[i-1] = parseInt(dirPaths[i]);
                        }
                    }
                    this.departmentForm.parent = tmp; //根据dirpath构造数组
                }
            },

            //显示新增界面
            handleAdd: function () {
                this.departmentFormVisible = true;//显示新增弹出框
                this.departmentForm={
                    id: null,
                    name: '',
                    sn: '',
                    state: 0,
                    manager: null,
                    parent: null
                };
                this.getDeptTree();
            },

            //编辑
            save: function () {
                this.$refs.departmentForm.validate((valid) => {//在一次触发表单校验（理解）
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {})
							.then(() => {
                            this.departmentLoading = true;
                            //NProgress.start();
                            let para = Object.assign({}, this.departmentForm);
                            if(para.parent){
                                //从表单复制对象中得到parent
                                let parentArrey = para.parent;//[1,12]
                                //将parent数组的最后一个值拿出来（最后一个值才是我们选中的父部门）
                                let lastDeptId = parentArrey[parentArrey.length -1];//我当前选中的部门ID
                                //重新将parent属性赋值成 json对象
                                para.parent ={"id":lastDeptId};
                            }
                            this.$http.put("/department",para)
                                .then(result=>{
                                    result=result.data;
                                    this.departmentLoading=false;
                                    if (result.success){
                                        this.$message({
                                            message:"操作成功！",
                                            type:"success"
                                        });
                                        this.departmentFormVisible=false;
                                        this.page=1;
                                        this.getDepartments();
                                    }else {
                                        this.$message({
                                            message:result.message,
                                            type:"error"
                                        });
                                    }
                                })
                                .catch(result=>{
                                    this.departmentLoading=false;
                                    this.departmentFormVisible=false;
                                    this.$message({
                                        message:"系统错误",
                                        type:"error"
                                    });
                                })
                        });
                    }
                });
            },

            selsChange: function (sels) {//选中的所有行sels
                this.sels = sels;
            },

            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id);//[1,2]
                this.$confirm('确认删除选中记录吗？', '温馨提示', {
                    type: 'warning'
                }).then(() => {//返回框的确认按钮
                    this.listLoading = true;
                    this.$http.patch("/department",ids)
                        .then(result=>{
                            this.listLoading = false;
                            result = result.data;
                            if(result.success){//删除成功
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page = 1;//删除成功定位到第一页
                            }else{//后端删除失败
                                this.$message({
                                    message: result.message,
                                    type: 'error'
                                });
                            }
                            this.getDepartments();
                        })
                        .catch(result=>{
                            this.listLoading = false;
                            this.$message({
                                message: '系统异常',
                                type: 'error'
                            });
                        })
                }).catch(() => {//取消确认框
                });

        },

        getEmployees(){
            this.$http.get("/employee")
                .then(result=>{
                    result = result.data
                    if(result){
                        this.employees = result;
                    }
                })
        },

            getDeptTree() {
                this.$http.get("/department/tree")
                    .then(result => {
                        result = result.data;//List<Department>
                        if (result) {
                            this.deptTree = result;
                        }
                    })
            }
        },

		mounted() {
            this.getDepartments();
            this.getEmployees();
        }
	}

</script>

<style scoped>

</style>